<template>
  <div class="water-quality-container">
    <div class="water-quality-header">
      <div class="water-quality-time flexRow">
        <div class="water-quality-title">时间</div>
        <!-- <div class="query-btn-group"> -->
        <px-form ref="formRef" :model="queryParams" :inline="true" class="custom-form-ui search-form">
          <px-form-item label="时间范围" prop="date" style="width: 380px">
            <px-date-picker
              v-model="dateRange"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </px-form-item>
        </px-form>
        <div>
          <px-button type="primary" @click="handleQuery">查询</px-button>
          <px-button @click="resetQuery">重置</px-button>
        </div>
        <!-- </div> -->
      </div>
      <div class="flexRow">
        <div class="water-quality-title">空调种类</div>
        <div class="btn_con">
          <px-button
            v-for="item in tabsOption"
            :key="item.name"
            :type="activeName === item.name ? 'primary' : ''"
            @click="tabSelectHandler(item.name)"
            >{{ item.label }}</px-button
          >
        </div>

        <!-- <CustomTabs :tabList="tabsOption" :activeName="activeName" @tabSelect="tabSelectHandler" /> -->
      </div>
      <div class="flexRow">
        <div class="water-quality-title">水质指标</div>
        <div class="btn_con">
          <px-button
            v-for="item in waterQualityList"
            :key="item.id"
            :type="waterValue === item.itemValue ? 'success' : ''"
            @click="handleIndicator(item.itemDesc, item.itemValue)"
            >{{ item.itemName }}</px-button
          >
        </div>
      </div>
      <!-- <div class="water-quality-factor flexRow">
        <div class="water-quality-title">因子:</div>
        <div class="query-btn-group">
          <px-button>置换水量</px-button>
          <px-button>温度</px-button>
          <px-button>缓释剂加药量</px-button>
          <px-button>杀虫剂加药量</px-button>
          <px-button>PH调节剂加药量</px-button>
        </div>
      </div> -->
    </div>
    <div class="spc_con">
      <lineChart :key="midKey4" :width="600" :height="384" :options="spcOptions4" />
    </div>
    <!-- <waterLineChart ref="waterChartRef" :chartsLineDataObj="chartsLineDataObj" :waterQualityList="waterQualityList" :waterValue="waterValue" /> -->
  </div>
</template>
<script lang="ts" setup>
import { ref, markRaw, computed, onMounted, nextTick, onUnmounted, reactive, getCurrentInstance } from "vue";
import { queryChildByTypeCodeAndItemValue, queryTwoCorrelationFactorSAndResult, queryAl } from "@/api/machineClass";
import { getWaterAddDrugData } from "@/api/machineApi";
import lineChart from "@/views/machine/operation/environmentTestManage/components/lineChart/index.vue";

const { proxy }: any = getCurrentInstance();

const tabsOption = ref([
  {
    name: "MCHWConfig",
    label: "MCHW"
  },
  {
    name: "LCHWConfig",
    label: "LCHW"
  },
  {
    name: "HWConfig",
    label: "HW"
  },
  {
    name: "HHWConfig",
    label: "HHW"
  },
  {
    name: "CWConfig",
    label: "CW"
  },
  {
    name: "PCWConfig",
    label: "PCW"
  }
]);

const midKey4 = ref(Date.now());
const maxValue = computed(() => {
  const str = JSON.parse(waterQualityList.value.find(e => e.itemValue === waterValue.value)?.itemDesc.replace(/[\r|\n|\t]/g, "")).max;
  if (str || str === 0 || str === "0") return Number(str);
  return undefined;
});
const minValue = computed(() => {
  const str = JSON.parse(waterQualityList.value.find(e => e.itemValue === waterValue.value)?.itemDesc.replace(/[\r|\n|\t]/g, "")).min;
  if (str || str === 0 || str === "0") return Number(str);
  return undefined;
});

const valueUnit = computed(() => {
  return JSON.parse(waterQualityList.value.find(e => e.itemValue === waterValue.value)?.itemDesc.replace(/[\r|\n|\t]/g, "")).unit || "";
});

const spcOptions4 = ref({});

const formRef = ref(null);

const queryParams = ref({});

// 获取当月第一天
const getCurrentMonthF = () => {
  let date = new Date();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  let d = "01";
  m = m < 10 ? "0" + m : m;
  return [y, m, d].join("-");
};

// 获取当月最后一天
const getCurrentMonthL = () => {
  let date = new Date();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  let d: any = new Date(y, m, 0).getDate();
  m = m < 10 ? "0" + m : m;
  d = d < 10 ? "0" + d : d;
  return [y, m, d].join("-");
};

const strT = proxy.parseTime(new Date().getTime() - 3600 * 1000 * 24 * 180, "{y}-{m}-{d} {h}:{i}:{s}");
const endT = proxy.parseTime(new Date().getTime(), "{y}-{m}-{d} {h}:{i}:{s}");

const dateRange = ref([strT, endT]);

const positionList = ref([]);
const chartsLineDataObj = ref({});
const waterChartRef = ref(null);
const waterValue = ref("");
const activeName = ref("MCHWConfig");

const formatDate = timestamp => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${h}:${m}:${s}`;
};

const searchLine = async () => {
  // const params = {
  //   startTime: date === "" ? "" : date[0],
  //   endTime: date === "" ? "" : date[1],
  //   pointList: positionList.value,
  //   timePeriod: "day"
  // };
  const params = {
    startTime: dateRange.value[0],
    endTime: dateRange.value[1],
    subsystem: activeName.value,
    actualParamList: [waterValue.value]
  };
  const res: any = await getWaterAddDrugData(params);
  // console.log(res, "8888888888888888888888");
  let arr = [];
  if (res.listActual && res.listActual.length) {
    arr.push({
      pointValues: res?.listActual || [],
      indicatorName: res?.listActual[0].itemName
    });
  }
  // if (res.listPredicated && res.listPredicated.length) {
  //   arr.push({
  //     pointValues: res?.listPredicated || [],
  //     indicatorName: res?.listPredicated[0].itemName
  //   });
  // }

  const markLineArr = [
    {
      name: "规格线",
      show: maxValue.value ? true : false,
      yAxis: maxValue.value,
      lineStyle: {
        color: "#EF4444",
        wideh: "1",
        type: "dashed"
      },
      label: {
        position: "insideEndBottom",
        formatter: `规格线<${maxValue.value != null ? maxValue.value : ""}${valueUnit.value || ""}`,
        color: "#EF4444"
      }
    },
    {
      name: "规格线",
      show: minValue.value ? true : false,
      yAxis: minValue.value,
      lineStyle: {
        color: "#EF4444",
        wideh: "1",
        type: "dashed"
      },
      label: {
        position: "insideEndTop",
        formatter: `规格线>${minValue.value != null ? minValue.value : ""}${valueUnit.value || ""}`,
        color: "#EF4444"
      }
    }
  ];
  const markLineA = markLineArr
    .map(item => {
      if (!item.yAxis && item.yAxis !== 0) {
        return undefined;
      } else {
        return item;
      }
    })
    .filter(Boolean);
  const series: any = [
    {
      // data: [400, 400, 400, 400, 400, 400],
      data: res.listActual && res.listActual.length ? res.listActual.map(item => Number(item.testValue)) : [],
      itemStyle: {
        color: function (params) {
          if (res.listActual && res.listActual.length && params.dataIndex === res.listActual.length - 1) {
            return "#F59E0B";
          } else {
            return "#3B82F6";
          }
        }
      },
      type: "bar",
      name: res.listActual && res.listActual.length ? res.listActual[0].itemName : "",
      barMaxWidth: 20,
      markPoint: {
        symbol: "diamond",
        symbolSize: 20,
        symbolRotate: 180,
        symbolOffset: [0, -16],
        label: {
          position: "top",
          color: "#fff",
          backgroundColor: "#EF4444",
          padding: 6,
          borderRadius: 6,
          distance: -10,
          formatter: function (params) {
            const {
              data: { coord }
            } = params;
            return `加药：${coord[1]}`;
          }
        },
        itemStyle: {
          color: "#EF4444"
        },
        data: [
          // 动态计算超出控制线的柱子
          ...(function () {
            const controlLine = maxValue.value;
            const controlLine1 = minValue.value;
            const isMax = maxValue.value || maxValue.value == 0;
            const isMin = minValue.value || minValue.value == 0;
            const data = res.listActual && res.listActual.length ? res.listActual.map(item => Number(item.testValue)) : [];
            return data
              .map((value, index) => {
                if (isMax && !isMin) {
                  if (value >= controlLine) {
                    return {
                      name: "加药",
                      coord: [index, value], // 柱子坐标
                      symbolOffset: [0, -10] // 气泡偏移（避免遮挡柱子顶部）
                    };
                  }
                } else if (!isMax && isMin) {
                  if (value <= controlLine1) {
                    return {
                      name: "加药",
                      coord: [index, value], // 柱子坐标
                      symbolOffset: [0, -10] // 气泡偏移（避免遮挡柱子顶部）
                    };
                  }
                } else if (!isMax && !isMin) {
                  return null;
                } else if (isMax && isMin) {
                  if (value >= controlLine || value <= controlLine1) {
                    return {
                      name: "加药",
                      coord: [index, value], // 柱子坐标
                      symbolOffset: [0, -10] // 气泡偏移（避免遮挡柱子顶部）
                    };
                  }
                } else {
                  return null;
                }
              })
              .filter(Boolean); // 过滤掉未超标的柱子
          })()
        ]
      },
      markLine: {
        symbol: "none",
        data: markLineA
      }
      // yAxisIndex: ind
    }
  ];
  console.log(series, "8888888888888888888888");
  const name1 = tabsOption.value.find(item => item.name === activeName.value).label;
  const name2 = waterQualityList.value.find(item => item.itemValue === waterValue.value).itemName;
  const option = {
    color: ["#3B82F6"],
    title: {
      text: `Water Quality Prediction And Actual ${name1}_${name2}`,
      left: "center"
    },
    grid: {
      left: "30px",
      top: "15%",
      right: "0",
      bottom: "0",
      containLabel: true
    },
    tooltip: {
      trigger: "axis",
      confine: true,
      axisPointer: {
        type: "shadow"
      }
    },
    xAxis: {
      type: "category",
      boundarGap: false,
      data: res.listActual && res.listActual.length ? res.listActual.map(e => e.calcTime) : []
    },
    yAxis: {
      type: "value"
    },
    series: series
  };
  spcOptions4.value = option;
  midKey4.value = Date.now();
};

// 查询
const handleQuery = async () => {
  try {
    searchLine();
    // searchHot();
  } catch (err) {
    console.log(err);
  } finally {
    // tableLoading.value = false;
  }
};
//重置
const resetQuery = () => {
  dateRange.value = [strT, endT];
  handleQuery();
};
//获取空调下面的水质指标
const waterQualityList = ref<any>([]);
const getWaterQualityList = async () => {
  waterQualityList.value = await queryChildByTypeCodeAndItemValue({
    value: activeName.value,
    typeCode: "MCTS"
  });
  waterValue.value = waterQualityList.value[0].itemValue;
};
//
//点击指标
const handleIndicator = (itemDesc, value) => {
  positionList.value.push(JSON.parse(itemDesc).point_position);
  waterValue.value = value;
};
const tabSelectHandler = async selectName => {
  activeName.value = selectName;
  getWaterQualityList();
};

onMounted(async () => {
  await getWaterQualityList();
  searchLine();
});
const time = Date.now();
</script>
<style lang="scss" scoped>
.water-quality-container {
  display: flex;
  flex-flow: column nowrap;
  gap: 16px;
  width: 100%;

  .spc_con {
    width: 100%;
    height: 384px;
  }

  .water-quality-header {
    display: flex;
    flex-flow: column nowrap;
    gap: 12px;

    .flexRow {
      display: flex;
      flex-flow: row nowrap;
      gap: 12px;
      justify-content: flex-start;
      width: 100%;

      .water-quality-title {
        width: 100px;
        height: 30px;
        font-size: 14px;
        line-height: 30px;
        color: var(--px-text-color-regular);
        text-align: center;
        border: 1px solid var(--px-border-color);
        border-radius: 4px;
      }

      .btn_con {
        display: flex;
        flex: 1;
        flex-flow: row wrap;
        gap: 8px;

        :deep(.px-button) {
          margin: 0;
        }
      }
    }
  }
}

:deep(.px-form-item) {
  margin: 0;
}
</style>
